/* eslint-disable no-tabs */
import qs from 'querystring'
import { getIsnTpl, getIsnFeeTpl } from '@/views/tpl'
import { getCurWebsite, toDataNumbers } from '@/views/common'
import { http } from '@/utils/axios'
import { _float, addTotal } from '@/utils/index'

const pushSummary = (data = []) => {
  return data.map(e => {
    const data = e.data
    const total = (e.data && e.data[0] && e.data[0].total) || {}
    const obj = {}
    Object.keys(total).forEach(key => {
      if (key.indexOf('.') !== -1) {
        const trueKey = key.split('.')[1]
        obj[trueKey] = total[key]
      }
    })
    data.push({
      summary: {
        ...obj,
        groupName: '总计'
      },
      downLines: {
        ...obj
      },
      ...total
    })
    return {
      ...e,
      data
    }
  })
}

export default {
  methods: {
    _getFee (row) {
      return new Promise((resolve, reject) => {
        const { name, psw, code, children = [] } = row
        const baseUrl = getCurWebsite()
        const url = baseUrl + '/isn/getFee'
        const data = {
          username: name,
          pwd: psw,
          safecode: code,
          children: children.length ? children.map(e => e.name) : []
        }
        http({
          method: 'post',
          url,
          withCredentials: false,
          data
        })
          .then(res => {
            console.log(res)
            if (this.checkSuccess(res)) {
              resolve(res.data.data || [])
            } else {
              reject((res.data && res.data.message) || '请求失败')
            }
          })
          .catch(e => {
            reject((e && e.message) || '请求失败')
          })
      })
    },
    async getMemberFee (scope) {
      this.loading = true
      const { row, $index: i } = scope
      const { name } = row
      this.$set(this.accountList[i], 'statusText', '请求中...')
      this.loading = true
      try {
        const list = await this._getFee(row)
        const tplData = getIsnFeeTpl({ data: [{ name, data: list }], name })
        this.sendToMainProcess(name + '.html', tplData)
        this.$set(this.accountList[i], 'statusText', '请求成功')
      } catch (e) {
        this.$set(this.accountList[i], 'statusText', e || '请求失败')
      } finally {
        this.loading = false
      }
    },
    async getAllMemberFee () {
      const list = this.accountList
      const len = list.length
      if (!len) {
        return []
      }
      this.loading = true
      const task = []
      list.forEach((item, i) => {
        task.push(this._getFee(item))
        this.$set(this.accountList[i], 'statusText', '请求中...')
      })

      this.loading = true
      const results = await Promise.allSettled(task)
      this.loading = false
      const datas = []
      results.forEach((res, i) => {
        if (res.status === 'fulfilled') {
          this.$set(this.accountList[i], 'statusText', '请求成功')
          datas.push({
            name: list[i].name,
            data: (res.value || [])
          })
        } else {
          this.$set(this.accountList[i], 'statusText', res.reason || '请求失败')
        }
      })
      const name = datas.map(e => e.name).join('、')
      const tplData = getIsnFeeTpl({ data: datas, name: name })
      this.sendToMainProcess(name + '.html', tplData)

      console.log('datas')
      console.log(datas)
      console.log(name)
    },
    // 单个获取
    getIsnItemData (item, i) {
      this.loading = true
      const { startDate, endDate } = this
      let { name } = item
      this.$set(this.accountList[i], 'statusText', '请求中...')
      this._getIsnItem(item)
        .then(data => {
          if (startDate && endDate) {
            name = startDate.substring(5) + '-' + endDate.substring(5) + '——' + name
          }
          this.$set(this.accountList[i], 'statusText', '请求成功')
          data = data.filter(e => e.data && e.data.length && e.name)
          if (data && data.length) {
            const totalData = data.map(e => {
              return {
                ...e,
                data: addTotal(e.data)
              }
            })
            const result = pushSummary(toDataNumbers(totalData))
            const tplData = getIsnTpl({ data: result })
            this.sendToMainProcess(name + '.html', tplData)
          } else {
            this.$set(this.accountList[i], 'statusText', '数据为空')
            this.$message.info('请求数据为空')
          }
        })
        .catch(e => {
          console.log(e)
          this.$set(this.accountList[i], 'statusText', typeof e === 'string' ? e : '请求失败...')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 全部新款报表
    getAllIsnItemData (reGetList) {
      const list = reGetList || this.accountList
      const len = list.length
      if (!len) {
        return
      }
      let tempList = []
      let index = 0
      this.loading = true
      const callback = () => {
        if (this.waitExportList.length === 0) {
          return this.$message.info('请求数据为空')
        }
        const { startDate, endDate } = this
        let name = this.accountList.map(e => e.name).join('、')
        if (startDate && endDate) {
          name = startDate.substring(5) + '-' + endDate.substring(5) + '-' + name
        }
        const data = pushSummary(toDataNumbers(this.waitExportList))
        const tplData = getIsnTpl({ data })
        this.sendToMainProcess(name + '.html', tplData)
      }
      for (let i = 0; i < len; i++) {
        const item = list[i]
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getIsnItem(item)
          .then(r => {
            r = r.filter(e => e.data && e.data.length && e.name)
            if (r && r.length) {
              this.$set(this.accountList[itemIndex], 'statusText', '请求成功')
              const totalData = r.map(e => {
                return {
                  ...e,
                  data: addTotal(e.data)
                }
              })
              // resultList = resultList.concat(r)
              tempList[i] = totalData
            } else {
              this.$set(this.accountList[itemIndex], 'statusText', '数据为空')
            }
          })
          .catch(e => {
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', typeof e === 'string' ? e : '请求失败...')
          })
          .finally(() => {
            index = index + 1
            if (index === len) {
              tempList = tempList.filter(e => e)
              tempList.forEach(e => {
                this.waitExportList = this.waitExportList.concat(e)
              })
              this.loading = false
              this.checkExistErrorList(() => callback())
            }
          })
      }
    },
    _getIsnItem (item) {
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line no-unused-vars
        const { name, psw, code, level, children = [] } = item
        // eslint-disable-next-line no-unused-vars
        const { startDate, endDate } = this
        const data = qs.stringify({
          username: name || '',
          safecode: code || '',
          pwd: psw || '',
          date_start: startDate,
          date_end: endDate,
          children: children.length ? children.map(e => e.name) : []
          // username: 'XXHKTLT076SUB03',
          // pwd: 'AAAa1234',
          // safecode: '112233',
          // date_start: '06/10/2021',
          // date_end: '06/10/2021'
        })
        const baseUrl = getCurWebsite()
        const babaUrl = baseUrl + '/isn/gen'
        http({
          method: 'post',
          url: babaUrl,
          withCredentials: false,
          data
        }).then(res => {
          if (this.checkSuccess(res)) {
            const data = res.data.data || []
            data.forEach(item => {
              if (item.data) {
                item.data.forEach(item => {
                  if (item.downLines && item.downLines['40']) {
                    item.downLines = item.downLines['40']
                  }
                })
                item.data = _float(item.data)
              }
            })
            resolve(data)
          } else {
            console.log(res)
            const msg = res && res.data && (res.data.rawResponse || res.data.message)
            reject(msg || '接口返回失败了...')
          }
        }).catch(e => {
          console.log('get item isn data error: ')
          console.error(e)
          reject(e)
        })
      })
    }
  }
}
